package com.sduept.nwld.dataserver.manager.statistics;

import java.util.ArrayList;
import java.util.List;


import javax.inject.Inject;

import com.sduept.cim.ledger.total.model.PrimaryDeviceCount;
import com.sduept.cim.utils.CimUtils;
import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.manager.cim.PrimaryDeviceCountPersistenceManager;
import com.sduept.nwld.dataserver.manager.cim.PrimaryDeviceCountQueryManager;
import com.sduept.nwld.dataserver.model.countanalyse.ElectricityInfo;
import org.springframework.stereotype.Service;

/**
 * 发电机台数查询manager
 * @author huangyu
 * @Date 2019年7月17日
 */

@Service
public class ElectricityGenerationManager {

	@Inject
	private SuperDAO dao;
	@Inject
	private PrimaryDeviceCountQueryManager pdquery;


	public List<ElectricityInfo> getAllElectricityInfo() {
		return dao.findAll(ElectricityInfo.class);
	}

	public ElectricityInfo createOrUpdateElectricityInfo(ElectricityInfo tl) {
		return dao.createOrUpdate(tl, ElectricityInfo.class);
	}

	public void deleteElectricityInfo(String id) {
		dao.delete(id, ElectricityInfo.class);
	}
	public void deleteElectricityInfoByYear(Integer year) {
		dao.delete(ElectricityInfo.class, "year=?1", new Object[] {year});
	}

	/**
	 *  根据一次设备统计结果重新计算
	 * @param year
	 */
	public void countByPrimaryDeviceCount(int year) {
		deleteElectricityInfoByYear(year);
		List<PrimaryDeviceCount> list =  pdquery.countByEquipmentType(year,PrimaryDeviceCountPersistenceManager.StatisticType.generatingunit.getType());
		List<ElectricityInfo> lastYearList = getElectricityInfos(year-1, null);
		list.stream().forEach(action->{
			ElectricityInfo ei = new ElectricityInfo();
			ei.setVoltage((int) CimUtils.getStandVoltagelevel(action.getVoltageLevel()));
			ei.setYear(year);
			ei.setCount(action.getStatisticCount().intValue());
			yearIncreaseCount(lastYearList,ei);
			createOrUpdateElectricityInfo(ei);
		});
	}
	private void yearIncreaseCount(List<ElectricityInfo> lastYearList,ElectricityInfo ei) {
		ei.setNewAdd(ei.getCount());
		lastYearList.forEach(lt->{
			if((ei.getYear()-1) == lt.getYear()) {
				ei.setNewAdd(ei.getCount()-lt.getCount());
				return ;
			}
		});
	}

	/**
	 * 	根据年份、电压等级查询，参数可以为空，都为空查询全部
	 * @param year
	 * @param voltage
	 * @return
	 */
	public List<ElectricityInfo> getElectricityInfos(Integer year, Integer voltage) {
		String esql = " 1=1 ";
		List<Object> param = new ArrayList<Object>();
		if(null != year) {
			esql += " and year = ?";
			param.add(year);
		}
		if(null != voltage) {
			esql += " and voltage = ?";
			param.add(voltage);
		}
		return dao.findByCondition(ElectricityInfo.class, esql, param.toArray());
	}
}
